<template>
  <div class="delivery-tasks">
    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="订单编号">
          <el-input v-model="filterForm.orderNumber" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="filterForm.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="配送状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="待分配" value="pending" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="配送员">
          <el-select v-model="filterForm.deliveryStaffId" placeholder="请选择配送员" clearable>
            <el-option
              v-for="staff in deliveryStaff"
              :key="staff.id"
              :label="staff.name"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="task-list">
      <template #header>
        <div class="card-header">
          <span>配送任务列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleBatchAssign" :disabled="!selectedTasks.length">
              批量分配
            </el-button>
            <el-button type="success" @click="handleExport">导出数据</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="tasks"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="任务编号" width="100" />
        <el-table-column prop="order_number" label="订单编号" width="120" />
        <el-table-column prop="customer_name" label="客户名称" width="120" />
        <el-table-column prop="address" label="配送地址" min-width="200" />
        <el-table-column prop="delivery_staff_name" label="配送员" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending'"
              type="primary"
              link
              @click="handleAssign(row)"
            >
              分配配送员
            </el-button>
            <el-button
              v-if="row.status === 'delivering'"
              type="warning"
              link
              @click="handleUpdateStatus(row)"
            >
              更新状态
            </el-button>
            <el-button type="success" link @click="handleViewDetails(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 分配配送员对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      :title="currentTask ? '分配配送员' : '批量分配配送员'"
      width="50%"
    >
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="配送员">
          <el-select v-model="assignForm.deliveryStaffId" placeholder="请选择配送员">
            <el-option
              v-for="staff in availableDeliveryStaff"
              :key="staff.id"
              :label="staff.name"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="assignForm.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssign">确认分配</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="更新配送状态"
      width="50%"
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="状态">
          <el-select v-model="statusForm.status" placeholder="请选择状态">
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="statusForm.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatusUpdate">确认更新</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 筛选表单
const filterForm = reactive({
  orderNumber: '',
  customerName: '',
  status: '',
  deliveryStaffId: ''
})

// 任务列表数据
const tasks = ref([])
const selectedTasks = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 配送员列表
const deliveryStaff = ref([
  { id: 1, name: '配送员A', status: 'available' },
  { id: 2, name: '配送员B', status: 'available' },
  { id: 3, name: '配送员C', status: 'busy' }
])

// 可用配送员列表
const availableDeliveryStaff = ref([
  { id: 1, name: '配送员A', status: 'available' },
  { id: 2, name: '配送员B', status: 'available' }
])

// 对话框控制
const assignDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const currentTask = ref(null)

// 分配表单
const assignForm = reactive({
  deliveryStaffId: '',
  note: ''
})

// 状态更新表单
const statusForm = reactive({
  status: '',
  note: ''
})

// 获取状态样式
const getStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    delivering: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待分配',
    delivering: '配送中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status] || '未知'
}

// 获取优先级样式
const getPriorityType = (priority) => {
  const typeMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return typeMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const textMap = {
    high: '高优先级',
    medium: '中优先级',
    low: '低优先级'
  }
  return textMap[priority] || '未知'
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedTasks.value = selection
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchTasks()
}

// 重置筛选
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  handleSearch()
}

// 批量分配
const handleBatchAssign = () => {
  if (selectedTasks.value.length === 0) {
    ElMessage.warning('请选择要分配的任务')
    return
  }
  currentTask.value = null
  assignDialogVisible.value = true
}

// 单个分配
const handleAssign = (row) => {
  currentTask.value = row
  assignDialogVisible.value = true
}

// 更新状态
const handleUpdateStatus = (row) => {
  currentTask.value = row
  statusForm.status = row.status
  statusForm.note = ''
  statusDialogVisible.value = true
}

// 查看详情
const handleViewDetails = (row) => {
  // TODO: 实现查看详情功能
  console.log('查看任务详情:', row)
}

// 导出数据
const handleExport = () => {
  // TODO: 实现导出功能
  ElMessage.success('导出成功')
}

// 提交分配
const submitAssign = async () => {
  try {
    // TODO: 调用后端 API 进行分配
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('分配成功')
    assignDialogVisible.value = false
    fetchTasks()
  } catch (error) {
    console.error('分配失败:', error)
    ElMessage.error('分配失败')
  }
}

// 提交状态更新
const submitStatusUpdate = async () => {
  try {
    // TODO: 调用后端 API 更新状态
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    fetchTasks()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTasks()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTasks()
}

// 获取任务列表
const fetchTasks = async () => {
  loading.value = true
  try {
    // TODO: 调用后端 API 获取数据
    // 暂时使用模拟数据
    const mockTasks = [
      {
        id: 1,
        order_number: 'ORD20240301001',
        customer_name: '公司A',
        address: '北京市朝阳区建国路88号',
        delivery_staff_name: '配送员A',
        status: 'pending',
        priority: 'high',
        created_at: '2024-03-01 09:00:00'
      },
      {
        id: 2,
        order_number: 'ORD20240301002',
        customer_name: '公司B',
        address: '北京市海淀区中关村大街1号',
        delivery_staff_name: '配送员B',
        status: 'delivering',
        priority: 'medium',
        created_at: '2024-03-01 10:30:00'
      },
      {
        id: 3,
        order_number: 'ORD20240301003',
        customer_name: '公司C',
        address: '北京市西城区西单大悦城',
        delivery_staff_name: '配送员C',
        status: 'completed',
        priority: 'low',
        created_at: '2024-03-01 11:15:00'
      }
    ]
    
    tasks.value = mockTasks
    total.value = mockTasks.length
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchTasks()
})
</script>

<style scoped>
.delivery-tasks {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.task-list {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>